<?php 
/**
 * @name PHPVcode —— a simple form dentify code class
 * @author crazymus < QQ:291445576 >
 * @version 1.1.0
 * @licenced apache2.0
 * @updated 2015-09-19
 */
class PHPVcode{

	//配置项 
	protected static $config = array(
		//session键名 
		'key' => 'php_vcode',
		//验证码位数 默认四位 
		'length' => 4,
		//验证码字体大小 
		'font-size' => 20,
		//生成的图片宽高 单位px 
		'width' => 100,
		'height' => 40,
		//文本颜色 支持:blue/green/red/black
		'text-color' => 'blue'
	);
	
	/**
	 * @name 生成验证码 
	 * @param $config 配置项 参见上面
	 * @output 图片
	 */
	public static function show($config=null){
		//合并配置项 
		self::$config = array_merge(self::$config,$config);
		$config = self::$config;
		
		//创建一张图片 
		$im = imagecreatetruecolor($config['width'],$config['height']);
		//创建背景色 
		$fill_color = imagecolorallocate($im, 255,255,255);
		//创建文本颜色 
		$text_color_array = self::genTextColor($config['text-color']);
		$text_color = imagecolorallocate($im,$text_color_array[0],$text_color_array[1],$text_color_array[2]);
		//填充背景色 
		imagefilledrectangle($im, 0, 0, 299, 99, $fill_color);
		//加载字体文件  
		$font_file = dirname(__FILE__).'/arial.ttf';
		//生成随机验证码 
		$code = self::_randCode();		
		//将验证码存储到session中 
		$key = $config['key'];
		$_SESSION[$key] = $code;
		
		//将验证码写入图片 
		for($i=0;$i<strlen($code);$i++){
			$offset = $i*15;
			imagefttext($im,$config['font-size'],rand(-15,15),20+$offset,25, $text_color, $font_file,$code[$i]);
		}
		
		//增加干扰线到图片 
		imageline($im,0,rand(0,20),100,rand(20,40),$text_color);
		imageline($im,rand(0,50),0,rand(50,100),40,$text_color);
		
		//告知浏览器这是一张图片 
		header('Content-Type:image/png');
		//以png格式输出图片  
		imagepng($im);
		//销毁图片 
		imagedestroy($im);
	}
	
	/**
	 * @name 生成RGB颜色值 
	 * @param string 颜色
	 * @return array RGB颜色值 
	 */
	private static function genTextColor($color){
		
		$color_array = array();
		switch($color){
			case 'green':
			$color_array = array(17,173,17);
			break;
			
			case 'blue':
			$color_array = array(43,43,181);
			break;
			
			case 'red':
			$color_array = array(255,13,13);
			break;
			
			case 'black':
			$color_array = array(0,0,0);
			break;
			
			default:
			$color_array = array(25,9,77);
			break;
		}
		return $color_array;
	}
	
	/**
	 * @name 生成随机验证码 
	 * @return string 验证码 
	 */
	private static function _randCode(){
		//获取配置信息  
		$config = self::$config;
		//用于生成验证码的字符
		$arr  = array(
			'a','b','c','d','e','f','g',
			'h','i','j','k','l','m','n',
			'o','p','q','r','s','t',
			'u','v','w','x','y','z',
			'1','2','3','4','5','6','7','8','9'
		);
		
		$len = count($arr)-1;
		$code = '';
		//随机获取字符  
		for($i=1; $i<=$config['length']; $i++){
			$key  = rand(0, $len);
			$code.= $arr[$key];
		}
		return $code;
	}
}


?>